# -*- coding: utf-8 -*-
import time
import flask_restful
from app.common.extensions import babel,hash_ids,login_manager
from flask import Flask,g,abort, jsonify,request,redirect
from app.models.database import db
from app.common import code, pretty_result

app = Flask(__name__)

# 保留flask原生异常处理
handle_exception = app.handle_exception
handle_user_exception = app.handle_user_exception


@app.before_request
def app_before_request():
    if not request.path=='/':
        api_key = request.args.get('api_key')
        if not api_key:
            return pretty_result(code=code.PARAM_ERROR,msg='api_key不能为空',data={})
        else:
            print('success')


def _custom_abort(http_status_code, **kwargs):
    """
    自定义abort 400响应数据格式
    """
    if http_status_code == 400:
        message = kwargs.get('message')
        if isinstance(message, dict):
            param, info = list(message.items())[0]
            data = '{}:{}!'.format(param, info)
            return abort(jsonify(pretty_result(code.PARAM_ERROR, data=data)))
        else:
            return abort(jsonify(pretty_result(code.PARAM_ERROR, data=message)))
    return abort(http_status_code)


def _access_control(response):
    """
    解决跨域请求
    """
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET,HEAD,PUT,PATCH,POST,DELETE'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
    response.headers['Access-Control-Max-Age'] = 86400
    return response


def create_app(config):
    """
    创建app
    """
    # 添加配置
    app.config.from_object(config)
    # 解决跨域
    app.after_request(_access_control)
    # 自定义abort 400 响应数据格式
    flask_restful.abort = _custom_abort
    # 数据库初始化
    db.init_app(app)

    # 登陆初始化
    login_manager.init_app(app)
    
    register_extensions(app)
    # 注册蓝图
    register_blueprints(app)
    # 使用flask原生异常处理程序
    register_extensions(app)

    def get_locale():
        """Returns the locale to be used for the incoming request."""
        return request.accept_languages.best_match(config.SUPPORTED_LOCALES)

    if babel.locale_selector_func is None:
        babel.locale_selector_func = get_locale

    @app.before_request
    def before_request():
        """Prepare some things before the application handles a request."""
        g.request_start_time = time.time()
        g.request_time = lambda: '%.5fs' % (time.time() - g.request_start_time)

    return app

def register_extensions(app):
    app.handle_exception = handle_exception
    app.handle_user_exception = handle_user_exception

def register_extensions(app):
    """Register extensions with the Flask application."""
    babel.init_app(app)

def register_blueprints(app):
    """Register blueprints with the Flask application."""
    from app.routes.api_v1 import api_v1
    from app.api.user import user
    app.register_blueprint(api_v1, url_prefix='/api/v1')
    app.register_blueprint(user, url_prefix='/api/v1/')
